package com.xpgk.plugin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.jfinal.config.Constants;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import com.jfinal.upload.OreillyCos;
import com.oreilly.servlet.multipart.FileRenamePolicy;
import com.xpgk.tools.ToolRandoms;

/**
 * 配置文件上传命名策略
 */
public class FileRenamePlugin implements IPlugin {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(FileRenamePlugin.class);
	public static final FileRenamePlugin instance = new FileRenamePlugin();
	@Override
	public boolean start() {
		OreillyCos.setFileRenamePolicy(new FileRenamePolicy() {
			@Override
			public File rename(File file) {
				String ext = "";   
		        int pot = file.getName().lastIndexOf(".");   
		        if(pot != -1){   
		        	ext = file.getName().substring(pot);   
		        }
		        String newName = ToolRandoms.getUuid(true) + ext;   
		        file = new File(file.getParent(), newName);   
		        return file;
			}
		});
		
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}
	
//	// 随机一个文件名
    public String randomFileName() {
        Date dt = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyMMddHHmmssSSS");
        String fileName = sdf.format(dt);
        return fileName;
    }
	
	/**
     * 修改文件名
     * @param filePath
     *            eg:D:/gai.jpg
     * @return
     */
    public String changeFileName(String filePath,String extension) {
        File file = new File(filePath);// 指定文件名及路径
        String name = randomFileName()+extension;
        //文件夹位置
        String path = filePath.substring(0, filePath.lastIndexOf("/"));
        String newFilePath = path+"/"+name;
        file.renameTo(new File(newFilePath)); // 改名
        return name;
    }
	
	
}
